import { Component, Input, Output, OnInit, AfterViewInit, AfterViewChecked, EventEmitter } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Assembly, AssemblyStyles, AssemblyValidators, AssemblyConfigs } from '../fb-design.model';
import { FormDesignService } from '../fb-design.service';
import { MdlSnackbarService } from '@angular-mdl/core';
import { DynamicFormValueService } from './fb-dynamic-form.service';
@Component({
    selector: 'fb-dynamic-form',
    templateUrl: './fb-dynamic-form.component.html',
    styleUrls: ['./fb-dynamic-form.component.scss'],
    providers: [FormDesignService, DynamicFormValueService]
})
export class FbDynamicFormComponent implements OnInit, AfterViewInit, AfterViewChecked {
    @Input() names: [];
    @Input() mode: number; //1:设计模式; 2:编辑模式
    @Output() onAssemblyClickEmitter = new EventEmitter<Assembly>();

    currentAssemblies: Assembly[];
    @Input()
    set assemblies(assemblies: Assembly[]) {
        if (assemblies.length > 0) {
            this.buildForm(assemblies);
            this.currentAssemblies = assemblies;
        } else {
            this.currentAssemblies = [];
        }
    }
    get assemblies(): Assembly[] { return this.currentAssemblies }
    maskstyle: any;

    form: FormGroup;
    formErrors: any = {};
    constructor(
        private formDesignService: FormDesignService,
        private dynamicFormValueService: DynamicFormValueService,
        private mdlSnackbarService: MdlSnackbarService) {
    }

    ngOnInit() {
        //初始化FormGroup对象
        this.form = new FormGroup({});
        if (this.mode == 1) {
            //1:设计模式（可拖拽，不可填写）; 
            this.maskstyle = { 'position': 'absolute', 'z-index': '2', 'height': '100%', 'width': '100%' }
        } else if (this.mode == 2) {
            //2:编辑模式（可填写不可拖拽）
            this.maskstyle = { 'position': 'absolute', 'z-index': '-1', 'height': '100%', 'width': '100%' }
        }
    }

    ngAfterViewInit() { }

    ngAfterViewChecked() {
        if (this.mode == 1) {
            $("#form-assembly-container .draggable").draggable({
                containment: "#formContentArea",
                drag: function (event, ui) {
                    if ($(this).position().top >= $("#formContentArea form").height() - $(this).height()) {
                        $("#formContentArea form").height($("#formContentArea form").height() + 100);
                        $("#formContentArea").scrollTop($("#formContentArea form").height() + 100);
                    }
                    var x = ui.offset.left;
                    var y = ui.offset.top - 65;
                    $('#mm').css("top", y);
                    $('#nn').css("height", $(document).height());
                    $('#nn').css("left", x);
                    $('#mm').css("display", "block");
                    $('#nn').css("display", "block");
                },
                stop: function (event, ui) {
                    $('#mm').css("display", "none");
                    $('#nn').css("display", "none");
                }
            });
        }
    }


    //鼠标拖动结束，更新组件位置信息
    mouseup(event, assembly) {
        assembly.attributes.x = parseInt($("#" + assembly.id).css("left").replace("px", ""));
        assembly.attributes.y = parseInt($("#" + assembly.id).css("top").replace("px", ""));
        assembly.attributes.refreshStyle();
        this.onAssemblyClickEmitter.emit(assembly);
        this.formDesignService.moveAssembly(assembly.id, assembly.attributes.x, assembly.attributes.y).subscribe()

    }

    /** 验证表单是否修改 */
    isDitry() {
        return this.form.dirty;
    }

    /** 文书保存 */
    onSubmit(recId, ver, formId, bizId, saveFlag: boolean = true) {
        this.onValueChanged(null, true);
        let hasError = false;
        for (let prop in this.formErrors) {
            if ('' != this.formErrors[prop]) {
                hasError = true;
                return;
            }
        }
        if (hasError) return;
        let formValueArray = [];
        let formValue = this.form.value;
        for (let prop in formValue) {
            this.assemblies.forEach(e => {
                if (prop == e.id + '') {
                    let value = { id: prop, name: e.name, value: formValue[prop] };
                    //图片组件单独获取值
                    if (e.controlType == 'image') {
                        value['value'] = e.value;
                    }
                    //dropdown控件为空,设置第一个选项为默认选中
                    if(e.controlType == 'dropdown'){
                        let selectedValue = formValue[prop];
                        if('' == selectedValue){
                            let items = JSON.parse(e.configs.items);
                            value['value'] = items[0]['value'];
                        }
                    }
                    //选择控件，保存label
                    if (e.controlType == 'radio' || e.controlType == 'dropdown' || e.controlType == 'checkbox') {
                        debugger
                        let items = JSON.parse(e.configs.items);
                        let valueArray = [];
                        if (formValue[prop] instanceof Array) {
                            valueArray = formValue[prop];
                        } else {
                            if(formValue[prop]){
                                valueArray = formValue[prop].split(',');
                            }  
                        }
                        let labelValue = '';
                        if (valueArray) {
                            items.forEach(e => {
                                valueArray.forEach(v => {
                                    if (v == e.value) {
                                        if ('' == labelValue) {
                                            labelValue = e.label;
                                        } else {
                                            labelValue = labelValue + "," + e.label;
                                        }
                                        return;
                                    }
                                })
                            });
                        }
                        formValueArray.push({ id: -prop, name: e.labelName, value: labelValue })
                    }
                    //表格控件
                    if (e.controlType == 'table') {
                        value['value'] = e.value;
                    }
                    formValueArray.push(value);
                    return;
                }
            });
        }
        let value = {
            'formId': formId,
            'formVersion': ver,
            'relKey': recId,
            'bizId': bizId,
            'formValue': JSON.stringify(formValueArray)
        };
        if(saveFlag){
            let value = 'formId='+formId+'&formVersion='+ver+'&relKey='+recId+'&bizId='+bizId+'&formValue='+JSON.stringify(formValueArray);
            this.dynamicFormValueService.saveUpdateFormValue(value).subscribe(data => {
                this.mdlSnackbarService.showToast('保存成功')
            });
        }else{
            return value;
        }
    }

    /** 获取表单值*/
    onLoadValue(recId, ver, formId, actDefId, bizId) {
        this.formDesignService.loadAssembliesByFormId(formId, actDefId).subscribe(data => {
            let array = [];
            data.forEach(ele => {
                let temp = new Assembly(ele);
                temp.name = ele.assemblyName;
                temp.labelName = ele.assemblyLabelName;
                temp.value = ele.assemblyValue;
                //样式
                if (ele.styleAttributes) {
                    temp.attributes = new AssemblyStyles(JSON.parse(ele.styleAttributes));
                    temp.attributes.x = ele['positionX'];
                    temp.attributes.y = ele['positionY'];
                }
                //验证
                temp.validators = new AssemblyValidators(ele.validAttributes ? JSON.parse(ele.validAttributes) : {});
                //配置
                temp.configs = new AssemblyConfigs(ele.configAttributes ? JSON.parse(ele.configAttributes) : {});
                temp.attributes.refreshStyle();
                array.push(temp);
            });
            this.assemblies = array;
            this.dynamicFormValueService.loadFormValue({
                'bizId': bizId,
                'relKey': recId,
                'formVersion': ver,
                'formId': formId
            }).subscribe(data => {
                let temp = this.assemblies;
                let fromVale = [];
                if (data) {
                    fromVale = JSON.parse(data.formValue);
                }
                fromVale.forEach(v => {
                    temp.forEach(ass => {
                        if (v['id'] == ass['id'] + '') {
                            ass['value'] = v['value'];
                            return;
                        }
                    });
                });
                this.assemblies = temp;
                try {
                    this.buildForm(this.assemblies);
                } catch (e) { }

            });
            this.buildForm(this.assemblies);
        });
    }
    buildForm(assemblies: any[]) {
        let group = {};
        this.formErrors = {};
        assemblies.forEach(assembly => {
            if (assembly.controlType != 'line' && assembly.controlType != 'text') {
                let valilations = [];
                //必填校验
                if (assembly.validators.required) {
                    valilations.push(Validators.required);
                }
                //最大长度校验
                if (assembly.validators.maxLength) {
                    valilations.push(Validators.maxLength(assembly.validators.maxLength));
                }
                //最小长度校验
                if (assembly.validators.minLength) {
                    valilations.push(Validators.minLength(assembly.validators.minLength));
                }
                //格式正则校验
                if (assembly.validators.pattern) {
                    valilations.push(Validators.pattern(assembly.validators.pattern));
                }
                group[assembly.id] = new FormControl(assembly.value || '', valilations);
                this.formErrors[assembly.id] = '';
            }
        });
        this.form = new FormGroup(group);
        this.form.valueChanges.subscribe(data => this.onValueChanged(data));
    }

    onValueChanged(data: any, dity: boolean = false) {
        if (!this.form) { return; }
        const form = this.form;
        let temp = this.formErrors;
        for (const field in temp) {
            temp[field] = '';
            const control = form.get(field);
            if (dity) {
                for (const key in control.errors) {
                    temp[field] = this.messages[key];
                }
            } else {
                if (control && control.dirty && !control.valid) {
                    for (const key in control.errors) {
                        temp[field] = this.messages[key];
                    }
                }
            }
        }
        this.formErrors = temp;
    }

    messages = {
        'required': '该字段为必填项.',
        'minlength': '长度不够.',
        'maxlength': '长度超标.',
        'pattern': '格式不正确'
    }
}
